<template>
	<view class="content">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view class="nav-header">
			<view class="item-colum" @click="goBack">
				<view class="item btn-icon">
					<u-image 
						src="/static/images/icon/left-icon.png"
						width="36rpx"
						height="36rpx"
					></u-image>
				</view>
			</view>
			<view class="item-colum">
				<view class="item">
					<u-image
						src="/static/images/icon/shopping.png"
						width="36rpx"
						height="36rpx"
					></u-image>
					<view class="title">預約下單</view>
				</view>
			</view>
			<view class="item-colum">
				
			</view>
		</view>
		<!--body-->
		<view class="body">
			<view class="body-card">
				<view class="card-item flex-left">
					<u-image
						:src="archives.cover"
						width="128rpx"
						height="150rpx"
						radius="20rpx"
					></u-image>
					<view style="margin-left: 20rpx;">
						<view style="color: #232426;font-size: 28rpx;font-weight: 600; ">{{archives.title}}</view>
						<view style="display: flex;justify-content: flex-start;align-items: baseline;color: #27C5D6;margin-top: 16rpx;gap: 10rpx;">
							<view style="font-size: 28rpx;">NT$</view>
							<view style="font-size: 32rpx;">{{archives.price}}</view>
							<view style="font-size: 22rpx;">/</view>
							<view style="font-size: 22rpx;">{{unitString}}</view>
						</view>
					</view>
				</view>
				<view class="card-item flex-between">
					<view class="title">OR 達人</view>
					<view class="value">{{expertUserInfo.nickname}}</view>
				</view>
				<view class="card-item flex-between">
					<view class="title">服務類型</view>
					<view class="value">{{archives.channelString}}</view>
				</view>
				<view class="card-item flex-between" v-if="archives.service_type == 2">
					<view class="title">到店地址</view>
					<view style="display: flex;justify-content: flex-start;gap: 12rpx;align-items: center;width: 75%;">
						<view class="value">{{archives.address}}</view>
						<view @click="showAddressFn">
							<u-image
								src="/static/images/icon/warning-circle.png"
								width="36rpx"
								height="36rpx"
							></u-image>
						</view>
					</view>
				</view>
			</view>
			
			<view style="padding:0 32rpx;margin-top: 48rpx;">
				<view style="background-color: #FFF;border-radius: 24rpx;padding-bottom: 40rpx;">
					<view style="padding:0 8rpx;display: flex;justify-content: space-between;align-items: center;align-self: stretch;">
						<view @click="prevWeek">
							<u-image
								:src="prevUrl"
								width="36rpx"
								height="36rpx"
							></u-image>
						</view>
						<view v-for="(item, index) in weekList" :key="index" >
							<view :class="{'week-item':week!=item.id,'week-item-active':week==item.id}" @click="changeWeek(item.id, item.title)">
								{{item.title}}
								<view style="font-size: 24rpx;">
									{{item.month}}/{{item.day}}
								</view>
							</view>
						</view>
						<view @click="nextWeek">
							<u-image
								:src="nextUrl"
								width="36rpx"
								height="36rpx"
							></u-image>
						</view>
					</view>
					<view style="width: 100%;height: 1rpx;background-color: #F6F8FA;"></view>
					<view style="padding: 40rpx 32rpx 0;box-sizing: border-box;">
						<view style="display: flex;justify-content: space-between;">
							<view v-for="(item, index) in dateList" :key="index">
								<view style="color: #BEC0C5;font-size: 24rpx;line-height: 140%;text-align: center;">{{item.title}}</view>
								<view v-for="(item_, index_) in item.children" :key="index_">
									<view 
										v-if="item_.status == 1"
										:class="{'day-item':!checkExistInSimpleArray(item_.id), 'day-item-active':checkExistInSimpleArray(item_.id)}" 
										@click="checkItem(item_.id)"
									>
										{{item_.title}}
									</view>
									<view
										v-else
										class="day-item-undisable" 
									>
										{{item_.title}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="body-card" style="margin-top: 24rpx;">
				<view class="card-item flex-between">
					<view class="title">您的姓名<span style="color: red;">*</span></view>
					<view>
						<u-input 
							placeholder="填寫姓名"
							border="none"
							inputAlign="right"
							v-model="form.username"
						></u-input>
					</view>
				</view>
				<view class="card-item flex-between">
					<view class="title">您的手機<span style="color: red;">*</span></view>
					<view>
						<u-input
							placeholder="填寫手機"
							border="none"
							inputAlign="right"
							v-model="form.mobile"
						></u-input>
					</view>
				</view>
				<view class="card-item flex-between" @click="openAreaFn" v-if="archives.service_type==1">
					<view class="title">服務地址<span style="color: red;">*</span></view>
					<view style="display: flex;justify-content: flex-end;align-items: center;width: 70%;">
						<view style="font-size: 28rpx;color: #BEC0C5;">{{holderArr.address}}</view>
						<view>
							<u-image
								src="/static/images/icon/right-icon.png"
								width="32"
								height="32"
							></u-image>
						</view>
					</view>
				</view>
				<view class="card-item flex-between">
					<view class="title">備註</view>
					<view>
						<u-input
							placeholder="填寫備註"
							border="none"
							inputAlign="right"
							v-model="form.remark"
						></u-input>
					</view>
				</view>
			</view>
			
			<view class="body-card" style="margin-top: 24rpx;display: none;">
				<u-radio-group v-model="payType">
					<!-- <view class="card-item flex-between">
						<view>
							<view class="title">OR 錢包支付</view>
							<view style="color: #1AAEC0;font-size: 24rpx;margin-top: 12rpx;">OR金幣剩餘 {{userInfo.money}}</view>
						</view>
						<view>
							<u-radio name="wallet" shape="circle" activeColor="#27C5D6" inactiveColor="#E5E6E8" size="36rpx" iconSize="32rpx" iconColor="#FFF" ></u-radio>
						</view>
					</view> -->
					<view class="card-item flex-between">
						<view>
							<view style="display: flex;justify-content: flex-start;align-items: center; ">
								<view class="title" style="margin-right: 16rpx;">信用卡支付</view>
								<view style="margin-right: 8rpx;">
									<u-image
										src="/static/images/icon/Mastercard.png"
										width="68rpx"
										height="48rpx"
									></u-image>
								</view>
								<view style="margin-right: 8rpx;">
									<u-image
										src="/static/images/icon/JCB.png"
										width="68rpx"
										height="48rpx"
									></u-image>
								</view>
								<view style="margin-right: 8rpx;">
									<u-image
										src="/static/images/icon/Visa.png"
										width="68rpx"
										height="48rpx"
									></u-image>
								</view>
								<view>
									<u-image
										src="/static/images/icon/UnionPay.png"
										width="68rpx"
										height="48rpx"
									></u-image>
								</view>
							</view>
							<view style="color: #BEC0C5;margin-top: 12rpx;font-size: 24rpx;">信用卡支付將扣手續費 3%</view>
						</view>
						<view>
							<u-radio name="card" shape="circle" activeColor="#27C5D6" inactiveColor="#E5E6E8" size="36rpx" iconSize="32rpx" iconColor="#FFF" ></u-radio>
						</view>
					</view>
					<view class="card-item flex-between">
						<view>
							<view style="display: flex;justify-content: flex-start;align-items: center; ">
								<view class="title">Apple Pay</view>
								<view style="margin-left: 16rpx;">
									<u-image
										src="/static/images/icon/ApplePay.png"
										width="68rpx"
										height="48rpx"
									></u-image>
								</view>
							</view>
							<view style="color: #BEC0C5;margin-top: 12rpx;font-size: 24rpx;">Apple Pay 將扣手續費 3%</view>
						</view>
						<view>
							<u-radio name="applePay" shape="circle" activeColor="#27C5D6" inactiveColor="#E5E6E8" size="36rpx" iconSize="32rpx" iconColor="#FFF" :disabled="true" ></u-radio>
						</view>
					</view>
				</u-radio-group>
			</view>
		</view>
		
		<!--底欄-->
		<view style="position: fixed;bottom: 0;left: 0; width: 100%;box-sizing: border-box;border-top: 1rpx solid #F6F8FA;padding: 20rpx 24rpx 60rpx;z-index: 999;background-color: #FFF;">
			<view style="display: flex;justify-content: space-between;width: 100%;align-items: center;">
				<view>
					<view style="font-size: 22rpx;color: #232426;">訂單金額</view>
					<view style="color: #27C5D6;font-size: 32rpx;font-weight: 500;">NT$ {{formattedSubtotal}}</view>
				</view>
				<view @click="checkOrder" style="border-radius: 200rpx;background-color:#27C5D6;color: #FFF;text-align: center; ">
					<view style="padding:16rpx 200rpx;gap: 12rpx;font-size: 28rpx;">下一步</view>
				</view>
			</view>
		</view>
		<!--底欄結束-->
		
		<!--詳細地址說明-->
		<u-popup :show="showAddress" round="48rpx" mode="bottom" @close="closeAddressFn" @open="showAddressFn">
			<view style="display: flex;justify-content: space-between;align-items: center; padding: 0 40rpx;margin-top: 28rpx;">
				<view style="width: 120rpx;"></view>
				<view style="width: 120rpx;color: #232426;font-size: 30rpx;font-weight: 600;">詳細地址</view>
				<view style="width: 120rpx;display: flex;justify-content: flex-end;" @click="closeAddressFn">
					<u-image
						src="/static/images/icon/close.svg"
						width="60rpx"
						height="60rpx"
					></u-image>
				</view>
		    </view>
			<view style="margin: 56rpx 0;padding:0 40rpx;font-size: 28rpx;color: #232426;">
				為保護個人資訊，目前僅提供「城市街道名稱」。完整詳細地址將在訂單成立後才提供。
			</view>
		</u-popup>
		<!--詳細地址說明結束-->
		
		<!--服务费說明-->
		<u-popup :show="showTips" round="48rpx" mode="bottom" @close="closeTipsFn" @open="showTipsFn">
			<view style="display: flex;justify-content: space-between;align-items: center; padding: 0 40rpx;margin-top: 28rpx;">
				<view style="width: 120rpx;"></view>
				<view style="width: 180rpx;color: #232426;font-size: 30rpx;font-weight: 600;">服务费說明</view>
				<view style="width: 120rpx;display: flex;justify-content: flex-end;" @click="closeTipsFn">
					<u-image
						src="/static/images/icon/close.svg"
						width="60rpx"
						height="60rpx"
					></u-image>
				</view>
		    </view>
			<view style="margin: 56rpx 0;padding:0 40rpx;font-size: 28rpx;color: #232426;">
				平台將收取訂單金額的 {{ fee * 100 }}% 作為服務費，用於支付交易處理、系統維護、安全風控及客戶服務等相關運營成本，請確認後再提交申請。
			</view>
		</u-popup>
		<!--服务费說明結束-->
		
		<!--確認訂單-->
		<u-popup :show="showOrderDetails" round="48rpx" mode="bottom" @close="showOrderDetails=false" @open="showOrderDetails=true">
			<view style="display: flex;justify-content: space-between;align-items: center; padding: 0 40rpx;margin-top: 28rpx;">
				<view style="width: 120rpx;"></view>
				<view style="width: 120rpx;color: #232426;font-size: 30rpx;font-weight: 600;">確認訂單</view>
				<view style="width: 120rpx;display: flex;justify-content: flex-end;" @click="showOrderDetails=false">
					<u-image
						src="/static/images/icon/close.svg"
						width="60rpx"
						height="60rpx"
					></u-image>
				</view>
		    </view>
			<view class="popup-order-details">
				<view class="popup-order-start">
					<view>
						<u-image
							:src="archives.cover"
							width="68rpx"
							height="80rpx"
							radius="20rpx"
						></u-image>
					</view>
					<view class="popup-order-title" style="margin-left: 20rpx;">
						{{archives.title}}
					</view>
				</view>
				<view class="popup-order-between popup-order-item">
					<view class="popup-order-title">時間</view>
					<view class="popup-order-title">{{selectedDate}} {{selectedTime}}</view>
				</view>
				<view class="popup-order-between popup-order-item">
					<view class="popup-order-title">服務方式</view>
					<view class="popup-order-title">{{archives.channelString}}</view>
				</view>
				<view class="popup-order-between popup-order-item" style="display: none;">
					<view class="popup-order-title">支付方式</view>
					<view class="popup-order-title">信用卡</view>
				</view>
				<view class="popup-order-line"></view>
				<view class="popup-order-between popup-order-item">
					<view class="popup-order-title">主要費用</view>
					<view class="popup-order-subtitle">NT$ {{formattedSubtotal}}</view>
				</view>
				<view class="popup-order-between popup-order-item">
					<view class="popup-order-between">
						<view class="popup-order-title">平台服務費</view>
						<view style="margin-left: 16rpx;" @click="showTipsFn">
							<u-image
								src="/static/images/icon/warning-circle.png"
								width="36rpx"
								height="36rpx"
							></u-image>
						</view>
					</view>
					<view class="popup-order-subtitle">{{ fee * 100 }}%</view>
				</view>
				<view class="popup-order-between popup-order-item">
					<view class="popup-order-title">總金額</view>
					<view class="popup-order-subtitle">NT$ {{formattedTotal}}</view>
				</view>
				<view class="popup-order-protocol">
					<view class="popup-order-start">
						<u-checkbox-group v-model="agreeProtocol">
							<u-checkbox name="agree" shape="circle" activeColor="#27C5D6" inactiveColor="#E5E6E8" size="36rpx" iconSize="32rpx" iconColor="#FFF"></u-checkbox>
						</u-checkbox-group>
						<view @click="toggleAgreeProtocol" style="font-size: 24rpx;color: #232426;">
							我已閱讀且同意《
						</view>
						<view @click="showContent" style="margin-left: 6rpx;font-size: 24rpx;color: #232426;border-bottom:2rpx solid #232426;">
							Only Rent 用戶協議
						</view>
						<view style="margin-left: 6rpx;font-size: 24rpx;color: #232426;">
							》
						</view>
					</view>
				</view>
				<view class="popup-order-protocol">
					<view @click="goPay" style="border-radius: 200rpx;background-color:#27C5D6;color: #FFF;text-align: center; ">
						<view style="padding:32rpx 200rpx;gap: 12rpx;font-size: 28rpx;">去付款</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!--確認訂單結束-->
		
	</view>
</template>

<script>
	import { archivesDetail, getConfig, preOrder, getUserInfo, createdEcPay, goPay } from '@/config/api.js';
	
	export default {
		
		data() {
			return {
				id:0,
				prevUrl:'/static/images/icon/left-icon-2.png',
				nextUrl:'/static/images/icon/right-icon-2.png',
				userInfo:{
					money:0
				},
				expertUserInfo:{
					nickname:'',
					avatar:'',
					bio:''
				},
				archives:{
					title:'',
					price:0,
					unitValue:'',
					updatetime:'',
					address:'',
					service_type:0,//1到府，2到店，3綫上
					cover:'',
					channel_string:'',
					nums:0
				},
				fee:0,
				monthIndex:0,//第幾周
				monthList:[],//當月日期列表
				week:1,//週幾
				weekList:[{
					id:1,
					title:'一'
				},{
					id:2,
					title:'二'
				},{
					id:3,
					title:'三'
				},{
					id:4,
					title:'四'
				},{
					id:5,
					title:'五'
				},{
					id:6,
					title:'六'
				},{
					id:0,
					title:'日'
				}],
				dateList:[],
				weekRes:[],//当前显示
				dateRes:[],//结果集
				payType:'wallet',
				showAddress:false,
				showTips:false,
				form:{
					username:'',
					mobile:'',
					address:'請輸入預服務地址',
					remark:'',
					maps:''
				},
				holderArr:{
					address:'請輸入預服務地址'
				},
				showOrderDetails:false,
				agreeProtocol:[],
				yuyueTimes:{},
				unitPrice:0,
				quantity:0,
				selectedDate: '', // 存储选择的日期 YYYY-MM-DD
				selectedTime: '' // 存储选择的时间 HH:00
			}
		},
		onLoad(option) {
			this.id = option.id;
			this.getContent();
			this.reloadWeek();
			this.getUserInfo();
			this.getUserInfo();
			this.getConfig();
		},
		computed:{
			totalPrice() {
			    return this.unitPrice * this.quantity
			},
			formattedSubtotal() {
				return this.formatCurrency(this.totalPrice)
			},
			formattedTotal() {
				return this.formatCurrency(this.totalPrice + this.totalPrice * this.fee )
			},
			unitString(){
				//單位1小時2天3單次
				return this.archives.unitValue == 1?this.archives.nums+'小時':this.archives.unitValue==2?this.archives.nums+'天':'每筆';
				// return this.archives.nums + unit;
			}
		},
		methods: {
			formatCurrency(num) {
			    return num.toFixed(2)
					.replace(/\d(?=(\d{3})+\.)/g, '$&,')
			},
			goBack(){
				uni.navigateBack();
			},
			// 获取默认日期（当前选中的周的第一天）
			getDefaultDate() {
				if (this.weekList && this.weekList.length > 0) {
				  const firstDay = this.weekList[0]; // 获取当前周的第一天
				  const currentYear = new Date().getFullYear();
				  return `${currentYear}-${firstDay.month.padStart(2, '0')}-${firstDay.day.padStart(2, '0')}`;
				}
				return '';
			},
			/**
			 * 獲取平臺服務費
			 */
			getConfig(){
				let that = this;
				let parames = {
					type:'fee'
				}
				getConfig({data:parames}).then((res) => {
					console.log(res)
					that.fee = res
				}).catch(() =>{
					
				})
			},
			getContent(){
				let that = this;
				uni.showLoading();
				
				archivesDetail({id:this.id}).then((res) => {
					//success
					uni.hideLoading();
					that.setContent(res)
				}).catch(() =>{
					
				})
			},
			setContent(info){
				console.log(info.cover)
				let that = this;
				//设置达人信息
				that.expertUserInfo.avatar = info.avatar;
				that.expertUserInfo.nickname = info.nickname;
				//設置訂單信息
				that.archives.title = info.title;
				that.archives.price = info.price.toLocaleString();
				that.archives.address = info.channel_address;
				that.archives.unitValue = info.unitValue;
				that.archives.service_type = info.service_type;
				that.archives.cover = info.cover;
				that.archives.address = this.truncateString(info.address);
				if( info.service_type == 1 ){
					that.archives.channelString = '到府';
				} else if( info.service_type == 2 ){
					that.archives.channelString = '到店';
				} else if(info.service_type == 3) {
					that.archives.channelString = '綫上';
				} else {
					that.archives.channelString = '其他';
				}
				
				//設置預約時間
				that.yuyueTimes['sunday'] = info.sunday;
				that.yuyueTimes['monday'] = info.monday;
				that.yuyueTimes['tuesday'] = info.tuesday;
				that.yuyueTimes['wednesday'] = info.wednesday;
				that.yuyueTimes['thursday'] = info.thursday;
				that.yuyueTimes['friday'] = info.friday;
				that.yuyueTimes['saturday'] = info.saturday;
				
				//设置用户可预约时间(周几)
				that.reloadYuyueTime('一')
				
				that.unitPrice = info.price;
				that.archives.nums = info.nums;
				
			},
			//截取地址
			truncateString(str, maxLength = 15) {
			    if (typeof str !== 'string') return '';
			    if (str.length <= maxLength) return str;
			    return str.substring(0, maxLength) + '...(部分隱藏)';
			},
			//初始化月份
			reloadWeek(){
				//當前日週幾
				const currentDate = new Date();
				const startMonday = this.getMonday(currentDate);
				// 计算一个月后的日期（基于30天）
				const tempEndDate = new Date(startMonday.getTime() + 30 * 24 * 60 * 60 * 1000);
				const endSunday = this.getSunday(tempEndDate);
				// 生成日期数组
				const dateArray = [];
				let currentDay = new Date(startMonday);
				while (currentDay <= endSunday) {
					dateArray.push(new Date(currentDay));
					currentDay = new Date(currentDay.setDate(currentDay.getDate() + 1));
				}
				// 按周分组
				const weeks = [];
				for (let i = 0; i < dateArray.length; i += 7) {
					
					weeks.push(dateArray.slice(i, i + 7));
				}
				const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
				let z = 1;
				for(let i = 0; i < weeks.length; i ++){
					let res = [];
					for(let j = 0; j < weeks[i].length; j ++){
						let obj = {
							id:z,
							title:weekdays[weeks[i][j].getDay()],
							month:String(weeks[i][j].getMonth() + 1),
							day:String(weeks[i][j].getDate()),
						}
						res.push(obj);
						this.dateRes.push([]);
						z++;
					}
					this.monthList.push(res);
				}
				this.weekList = this.monthList[this.monthIndex];
				// 设置默认选中的日期（当前周的第一天）
				this.selectedDate = this.getDefaultDate();

				// 设置默认选中的星期（星期一）
				this.week = 1;

				// 加载默认日期的时间段
				this.reloadYuyueTime('一');
			},
			getMonday(d) {
				const day = d.getDay();
				const diff = day === 0 ? 6 : day - 1; // 处理周日的情况
				const monday = new Date(d);
				monday.setDate(d.getDate() - diff);
				monday.setHours(0, 0, 0, 0);
				return monday;
			},
			getSunday(d) {
				const day = d.getDay();
				const diff = day === 0 ? 0 : 7 - day; // 若非周日，计算到周日所需天数
				const sunday = new Date(d);
				sunday.setDate(d.getDate() + diff);
				sunday.setHours(23, 59, 59, 999); // 设置为当天的最后一刻
				return sunday;
			},
			//检查基本类型数组
			checkExistInSimpleArray(id) {
				return this.weekRes.includes(id);
			},
			changeWeek(id,title){
				this.dateRes[this.week - 1] = this.weekRes;
				this.week = id;
				this.weekRes = this.dateRes[id-1];

				// 获取选择的日期
				const selectedDay = this.weekList.find(item => item.id === id);
				if (selectedDay) {
				const currentYear = new Date().getFullYear();
				this.selectedDate = `${currentYear}-${selectedDay.month.padStart(2, '0')}-${selectedDay.day.padStart(2, '0')}`;
				}

				// 切换日期时清空已选时间
				this.weekRes = [];
				this.selectedTime = '';
				this.quantity = 0;

				this.reloadYuyueTime(title);
				console.log('changeWeek', this.dateRes, 'selectedDate:', this.selectedDate)
			},
			checkItem(id){
				if(this.weekRes.includes(id)){
				    const index = this.weekRes.findIndex(item => item === id);
				    if (index !== -1) {
				      this.weekRes.splice(index, 1);
				      this.quantity--;
				      this.selectedTime = ''; // 清空选择的时间
				    }
				} else {
				    if( this.weekRes.length > 0 ){
				      uni.showToast({
				        title:'時間已選',
				        icon:'none'
				      })
				      return;
				}
				    
					this.weekRes.push(id);
					this.quantity++;
					
					// 设置选择的时间 (格式: HH:00)
					this.selectedTime = `${id.toString().padStart(2, '0')}:00`;
				}
				  
				console.log('selectedTime:', this.selectedTime);
			},
			prevWeek(){
				if(this.monthIndex <= 0){
					return;
				}

				this.dateRes[this.week - 1] = this.weekRes;

				this.monthIndex -= 1;
				this.weekList = this.monthList[this.monthIndex];

				// 更新选择的日期
				const selectedDay = this.weekList.find(item => item.id === this.week);
				if (selectedDay) {
					const currentYear = new Date().getFullYear();
					this.selectedDate = `${currentYear}-${selectedDay.month.padStart(2, '0')}-${selectedDay.day.padStart(2, '0')}`;
				}

				// 切换周时清空已选时间
				this.weekRes = [];
				this.selectedTime = '';
				this.quantity = 0;

				// 重新加载时间段
				const weekTitle = this.weekList.find(item => item.id === this.week)?.title || '一';
				this.reloadYuyueTime(weekTitle);

				this.nextUrl = '/static/images/icon/right-icon-2.png';
				if(this.monthIndex <= 0){
					this.prevUrl = '/static/images/icon/left-icon-2.png';
				} else {
					this.prevUrl = '/static/images/icon/left-icon.png';
				}
			},
			nextWeek(){
				if(this.monthIndex >= this.monthList.length-1){
					return;
				}

				this.dateRes[this.week - 1] = this.weekRes;

				this.monthIndex += 1;
				this.weekList = this.monthList[this.monthIndex];

				// 更新选择的日期
				const selectedDay = this.weekList.find(item => item.id === this.week);
				if (selectedDay) {
					const currentYear = new Date().getFullYear();
					this.selectedDate = `${currentYear}-${selectedDay.month.padStart(2, '0')}-${selectedDay.day.padStart(2, '0')}`;
				}

				// 切换周时清空已选时间
				this.weekRes = [];
				this.selectedTime = '';
				this.quantity = 0;

				// 重新加载时间段
				const weekTitle = this.weekList.find(item => item.id === this.week)?.title || '一';
				this.reloadYuyueTime(weekTitle);

				this.prevUrl = '/static/images/icon/left-icon.png';
				if(this.monthIndex >= this.monthList.length-1){
					this.nextUrl = '/static/images/icon/right-icon.png';
				} else {
					this.nextUrl = '/static/images/icon/right-icon-2.png';
				}
			},
			reloadYuyueTime(num){
				let day = 'monday';
				
				switch(num){
					case '二':
						day = 'tuesday';
						break;
					case '三':
						day = 'wednesday';
						break;
					case '四':
						day = 'thursday';
						break;
					case '五':
						day = 'friday';
						break;
					case '六':
						day = 'saturday';
						break;
					case '日':
						day = 'sunday';
						break;
					default:
						break;
				}
				
				let timeArray = [];
				let dayList = this.yuyueTimes[day];
				
				if( this.yuyueTimes[day] && this.yuyueTimes[day].length > 0 ){
					timeArray = dayList.split(',');
				}
				
				this.dateList = this.createWeekList(timeArray);
			},
			createWeekList(timeArray){
				const timePeriods = [
				    { id: 1, title: '凌晨', start: 0, end: 5 },
				    { id: 2, title: '早上', start: 6, end: 11 },
				    { id: 3, title: '傍晚', start: 12, end: 17 },
				    { id: 4, title: '晚上', start: 18, end: 23 }
				];
				
				return timePeriods.map(period => {
				    const children = [];
				    for (let i = period.start; i <= period.end; i++) {
				      const timeStr = `${i.toString().padStart(2, '0')}:00`;
				      children.push({
				        id: i,
				        title: timeStr,
				        status: timeArray.includes(timeStr) ? 1 : 0
				      });
				    }
				    return {
				      id: period.id,
				      title: period.title,
				      children
				    };
				});
			},
			checkOrder(){
				// 验证是否选择了日期和时间
				if (!this.selectedDate) {
				    uni.showToast({
				      title: '請選擇預約日期',
				      icon: 'none'
				    });
				    return;
				}
				  
				if (!this.selectedTime) {
				    uni.showToast({
				      title: '請選擇預約時間',
				      icon: 'none'
				    });
				    return;
				}
				this.showOrderDetails = true
			},
			goPay(){
				// 验证是否选择了日期和时间
				if (!this.selectedDate) {
				    uni.showToast({
				      title: '請選擇預約日期',
				      icon: 'none'
				    });
				    return;
				}
				  
				if (!this.selectedTime) {
				    uni.showToast({
				      title: '請選擇預約時間',
				      icon: 'none'
				    });
				    return;
				}
				
				// 检查是否同意协议
				if (!this.agreeProtocol.includes('agree')) {
					uni.showToast({
						title: '請同意用戶協議',
						icon: 'none'
					});
					return;
				}
				
				let that = this;
				let data = {
					fid:this.id,
					customer_name:this.form.username,
					customer_phone:this.form.mobile,
					customer_address:this.form.address,
					customer_map:this.form.maps,
					nums:1,
					paytype:1,
					price:this.totalPrice,
					remark:this.form.remark,
					times_id:`${this.selectedDate} ${this.selectedTime}`
				}
				preOrder(data).then((res) => {
					console.log('sucess', res)
					//success
					const order_number = res;
					const now = new Date();
					
					// #ifdef H5
					// web端測試跳轉
					uni.redirectTo({
						url: '/pages/order/result?order_number='+order_number
					});
					// #endif
					  
					// #ifdef APP-PLUS
					that.getPayToken(order_number);//APP端跳轉支付
					// #endif
					
					// return;
					
				}).catch((e) =>{
					console.log('error', e)
					
				})
			},
			getPayToken(order_number){
				let that = this;
				let data = {
					order_number:order_number
				}
				uni.showLoading({
					title:'支付跳轉中...'
				})
				createdEcPay(data).then((res) => {
					//success
					console.log('sucess', res)
					let token_ = res.data.Token
					
					uni.navigateTo({
						url:'/pages/index/index',
						events: {
							// 定义接收事件
							acceptData: (data) => {
								console.log('接收付款patoken:', data);
								that.payOrder(order_number, data.payToken)
							}
						},
						success: (res) => {
							uni.hideLoading();
							// 向B页面传递初始数据（可选）
							res.eventChannel.emit('initData', { 
								order_number: order_number,
								token:token_
							});
						}
					})
					
					
				}).catch((e) =>{
					console.log('error', e)
					
				})
			},
			payOrder(number,token){
				let that = this;
				let parames = {
					order_number:number,
					pay_token:token,
				}
				
				console.log(parames)
				uni.showLoading({
					title:'支付中...'
				})
				
				goPay(parames).then((res) => {
					//success
					console.log('sucess', res)
					
					uni.redirectTo({
						url: '/pages/order/result?order_number='+number
					});
					
					// if( res == 'success' ){
					// 	//支付成功
					// 	uni.navigateTo({
					// 		url: '/pages/order/result',
					// 		events: {
					// 			// 定义接收事件
					// 			acceptData: (data) => {
					// 				console.log('接收数据:', data);
					// 			}
					// 		},
					// 		success: (res) => {
					// 			// 向B页面传递初始数据（可选）
					// 			res.eventChannel.emit('initData', { 
					// 				order_nunmer: number
					// 			});
					// 		}
					// 	});
					// }
				}).catch((e) =>{
					console.log('error', e)
					
				})
			},
			openAreaFn(){
				let that = this;
				uni.navigateTo({
					url: '/pages/my/address',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.form.address = data.data.address;
							that.form.maps = data.data.maps;
							that.holderArr.address = data.data.address;
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			getUserInfo(){
				let that = this;
				getUserInfo().then((res) => {
					//success
					// that.userInfo = res.userInfo;
					
					let money = res.userInfo.money;
					money = Number(money)
					money = that.formatCurrency(money)
					that.userInfo.money = money
				}).catch(() =>{
					
				})
			},
			showContent(){
				uni.navigateTo({
					url:'/pages/index/content?type=agreement'
				})
			},
			showAddressFn(){
				this.showAddress = true;
			},
			closeAddressFn(){
				this.showAddress = false;
			},
			showTipsFn(){
				this.showTips = true;
				this.showOrderDetails = false;
			},
			closeTipsFn(){
				this.showTips = false;
				this.showOrderDetails = true;
			},
			toggleAgreeProtocol() {
				if (this.agreeProtocol.includes('agree')) {
					// 如果已经选中，则取消选中
					this.agreeProtocol = [];
				} else {
					// 如果未选中，则选中
					this.agreeProtocol = ['agree'];
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		background-color: #F4F6F7;
		min-height: 100vh;
		padding-bottom: 30rpx;
		
		.body{
			margin-top: 40rpx;
			padding-bottom: 130rpx;
		}
		
		.week-item{
			font-size: 32rpx;
			text-align: center;
			font-weight: 500;
			line-height: 140%;
			letter-spacing: 0.64rpx;
			padding: 32rpx 0 24rpx;
			color: rgba(190, 192, 197, 0.50);
		}
		.week-item-active{
			font-size: 32rpx;
			text-align: center;
			font-weight: 500;
			line-height: 140%;
			letter-spacing: 0.64rpx;
			padding: 32rpx 0 24rpx;
			color: #020202;
			border-bottom: 2rpx solid #020202;
		}
		.day-item{
			padding: 6px 15px;
			border-radius: 12px;
			background-color: #F6F8FA;
			color: #232426;
			font-size: 24rpx;
			margin-top: 32rpx;
		}
		.day-item-active{
			padding: 6px 15px;
			border-radius: 12px;
			background-color: #27C5D6;
			color: #fff;
			font-size: 24rpx;
			margin-top: 32rpx;
		}
		.day-item-undisable{
			padding: 6px 15px;
			border-radius: 12px;
			background-color: #FCFDFD;
			color: #CBCDD1;
			font-size: 24rpx;
			margin-top: 32rpx;
		}
		.u-radio-group--row{
			display: block !important;
			flex-direction: row !important;
		}
		
		.popup-order-details{
			margin: 56rpx 0;
			padding:0 40rpx;
			
			.popup-order-start{
				display: flex;
				justify-content: flex-start;
				align-items: center;
			}
			.popup-order-between{
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
			.popup-order-item{
				margin: 20rpx 0;
			}
			.popup-order-title{
				font-size: 28rpx;
				color: #232426;
				font-weight: 500;
			}
			.popup-order-subtitle{
				font-size: 28rpx;
				color: #1AAEC0;
				font-weight: 500;
			}
			.popup-order-line{
				width: 100%;
				height: 2rpx;
				background-color: #F4F6F7;
				margin: 24rpx 0;
			}
			.popup-order-protocol{
				margin: 56rpx 0;
				
			}
		}
	}
	
</style>
